<template>
  <el-row class="registerBox">
    <el-col class="centent">
      <el-form
        label-width="80px"
        label-position="right"
        :model="registerForm"
        ref="registerForm"
        :rules="rules"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="学号或者工号"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="registerForm.password"
            placeholder="建议6-12字符"
          ></el-input>
        </el-form-item>
        <el-form-item label="" prop="rePassword">
          <el-input
            type="password"
            v-model="registerForm.rePassword"
            placeholder="请再输一遍密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="通信邮箱" prop="email">
          <el-input
            type="email"
            v-model="registerForm.email"
            placeholder="用于接受审核结果的邮箱"
          ></el-input>
        </el-form-item>
        <el-form-item label="身份证明" prop="cateficate">
          <el-upload
            action="#"
            list-type="picture-card"
            ref="upload"
            accept=".jpeg,.jpg,.png"
            :auto-upload="false"
            :limit="1"
            :on-exceed="imageExceed"
            :http-request="handleUpload"
            class="upload_box"
          >
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{ file }">
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.url"
                fit="center"
                alt=""
              />
              <span class="el-upload-list__item-actions">
                <span @click="imageRemove(file)">
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
        </el-form-item>
        <el-button type="primary" @click="doRegister" style="float: right"
          >立即注册</el-button
        >
      </el-form>
    </el-col>
  </el-row>
</template>

<script>
import { Loading } from "element-ui";
import axios from "@/request/index";
import ossUpload from "@/aliyun-oss";

export default {
  name: "Register",
  data() {
    return {
      registerForm: {
        username: "",
        password: "",
        rePassword: "",
        email: "",
        cateficate: "",
      },
      rules: {
        username: [{ required: true, message: "用户名必填" }],
        password: [{ required: true, message: "密码必填" }],
        rePassword: [{ required: true, message: "请再次输入密码" }],
        email: [
          {
            required: true,
            validator: (rule, value, callback) => {
              let reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
              if (!reg.test(value)) {
                callback(new Error("请输入有效的邮箱"));
              } else {
                callback();
              }
            },
          },
        ],
        cateficate: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.$refs.upload.uploadFiles.length == 0) {
                callback(
                  new Error("身份证明照片必填（照片必须带有职工号或学号）")
                );
              } else {
                callback();
              }
            },
          },
        ],
      },
    };
  },
  methods: {
    handleUpload() {
      return new Promise(async (resolve, reject) => {
        await ossUpload(
          "certificate",
          this.$refs.upload.uploadFiles[0].raw
        ).then((res) => resolve(res));
      });
    },
    imageExceed() {
      this.$message.info("只需要上传一张照片就可以了");
    },
    imageRemove(file) {
      this.$refs.upload.uploadFiles = this.$refs.upload.uploadFiles.filter(
        (item) => {
          return item != file;
        }
      );
    },
    async doRegister() {
      let loading = Loading.service({
        target: ".centent",
        text: "正在提交注册信息",
        background: "rgba(236, 245, 255, 0.2)",
      });
      let passed = false;
      this.$refs.registerForm.validate((result, faildFields) => {
        passed = result;
      });
      if (!passed) {
        loading.close();
        return;
      }
      await this.handleUpload().then((res) => {
        this.registerForm.cateficate = res;
      });
      axios
        .post("/auth/register", {
          username: this.registerForm.username,
          password: this.registerForm.password,
          email: this.registerForm.email,
          certificate: this.registerForm.cateficate,
        })
        .then((res) => {
          if (res.data.code == 200) {
            loading.close();
            this.$message.success(res.data.data);
            this.$router.push({ name: "login" });
          } else {
            loading.close();
            this.$message.error(res.data.data);
          }
        })
        .catch((e) => {});
    },
  },
};
</script>

<style scoped>
.registerBox {
  height: 100%;
}

.centent {
  background-color: rgba(200, 200, 200, 0.6);
  padding: 30px 50px 20px 20px;
}

/* 文件上传 */
.upload_box >>> .el-upload {
  background: none;
}

.picture {
  width: 150px;
  height: 150px;
  display: block;
}
</style>